import React, { useEffect, useState } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { connect } from "react-redux";
import { Spin } from "antd";
import axios from "axios";
import Home from "../../views/sandBox/home/Home";
import UserList from "../../views/sandBox/user-manage/UserList";
import RoleList from "../../views/sandBox/right-manage/RoleList";
import RightList from "../../views/sandBox/right-manage/RightList";
import NoPermission from "../../views/sandBox/no-permission/NoPermission";
import NewsAdd from "../../views/sandBox/news-manage/NewsAdd";
import NewsDraft from "../../views/sandBox/news-manage/NewsDraft";
import NewsCategory from "../../views/sandBox/news-manage/NewsCategory";
import Audit from "../../views/sandBox/audit-manage/Audit";
import AuditList from "../../views/sandBox/audit-manage/AuditList";
import Unpublished from "../../views/sandBox/publish-manage/Unpublished";
import Published from "../../views/sandBox/publish-manage/Published";
import Sunset from "../../views/sandBox/publish-manage/Sunset";
import NewsPreview from "../../views/sandBox/news-manage/NewsPreview";
import NewsUpdate from "../../views/sandBox/news-manage/NewsUpdate";

const LocalRouterMap = {
  home: <Home />,
  "user-manage/list": <UserList />,
  "right-manage/role/list": <RoleList />,
  "right-manage/right/list": <RightList />,
  "news-manage/add": <NewsAdd />,
  "news-manage/draft": <NewsDraft />,
  "news-manage/category": <NewsCategory />,
  "news-manage/preview/:id": <NewsPreview />,
  "news-manage/update/:id": <NewsUpdate />,
  "audit-manage/audit": <Audit />,
  "audit-manage/list": <AuditList />,
  "publish-manage/unpublished": <Unpublished />,
  "publish-manage/published": <Published />,
  "publish-manage/sunset": <Sunset />,
};

function NewsRouter(props: { isLoading: boolean }) {
  const [backTouterList, setBackTouterList] = useState<Array<Irouter>>([]);
  useEffect(() => {
    Promise.all([axios.get("/rights"), axios.get("/children")]).then((res) => {
      const routes = [...res[0].data, ...res[1].data].map((item) => {
        item.key = item.key.slice(1);
        return item;
      });
      console.log(routes);
      setBackTouterList(routes);
    });
  }, []);

  interface Irouter {
    key: string;
    pagepermisson: string;
    routepermisson: string;
  }
  const checkRoute = (item: Irouter) => {
    // 判断本地路由表是否存在 && （是页面权限 || 是路由权限）
    return (
      LocalRouterMap[item.key as keyof typeof LocalRouterMap] &&
      (item.pagepermisson || item.routepermisson)
    );
  };
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("user") || "");
  const checkUserPermission = (item: Irouter) => {
    return rights.includes(`/${item.key}`);
  };

  return (
    <Spin spinning={props.isLoading}>
      <Routes>
        <Route path="home" element={<Home />}></Route>
        {backTouterList.map((e: Irouter) => {
          if (checkRoute(e) && checkUserPermission(e)) {
            return (
              <Route
                path={e.key}
                key={e.key}
                element={LocalRouterMap[e.key as keyof typeof LocalRouterMap]}
              ></Route>
            );
          } else {
            return null;
          }
        })}
        <Route path="/" element={<Navigate to="/home" />}></Route>
        <Route path="*" element={<NoPermission />}></Route>
      </Routes>
    </Spin>
  );
}

const mapStateToProps = ({
  LoadingReducer: { isLoading },
}: {
  LoadingReducer: { isLoading: boolean };
}) => {
  return {
    isLoading,
  };
};

export default connect(mapStateToProps)(NewsRouter);
